<?
	/**
	 * ITsnp
	 * v1.0
	 * ./class/page.class.php
	 * TODO:分页类。
	 * Create：2008-05-21
	 * Modify：2008-05-23
	 * Pocky@best WorkGroup.
	 * 使用方法
		$array = array('total'=>totalCount, 'perpage'=>count per page, 'url'=>指定链接的URL（optional）, 'page_name'=>分页的GET参数名(可选))
		$page = new page($array);	
		echo $page->show();//输出分页HTML代码。
		css 样式：index_page 当前页无链接效果  a 链接效果
	 */
	class page
	{
		var $page_name	=	'page';		//分页参数名
		var $first_page =	'<<';		//第一页
		var $last_page	=	'>>';		//最后页
		var $next_page	= 	'>';		//下页
		var $pre_page	=	'<';		//上页
		var $index_page =	1;			//当前页
		var $Before_page=	5;			//显示当前页的前后5页
		//构造函数
		function page($arr)
		{
			//检验参数是否为数组
			if(!is_array($arr))
			{
				$this->error(__FUNCTION__,'No Array.');
			}
	
			//检验是否自定义URL与自定义表单名
			array_key_exists('url',$arr) ? $this->url = $arr['url'] : '';
			array_key_exists('page_name',$arr) ? $this->page_name = $arr['page_name'] : '';
			
			//取得总页码
			$this->total_page = ceil(intval($arr['total'])/intval($arr['perpage']));
			
			//取得当前页码
			if(isset($_GET[$this->page_name]))
			{
				$this->index_page = $_GET[$this->page_name];
			}
		}
		
		//输出分页链接
		function show()
		{
			//首页，上页
			if($this->index_page>1)
			{
				$Nav .= "<A href=".$this->get_url().$this->page_name."=1>".$this->first_page."</a>";
				$Nav .= "<A href=".$this->get_url().$this->page_name."=".($this->index_page-1).">".$this->pre_page."</a>";
			}
			
			//循环获得当前页的前后页码
			for($i=$this->index_page-intval($this->Before_page);$i<=$this->index_page+intval($this->Before_page);$i++)
			{
				//相关页码必须大于0页，小等于总页码
				if($i>0 && $i<=$this->total_page)
				{
					//链接效果,对当前页不加链接
					($i!=$this->index_page) ? $Nav .= "<A href=".$this->get_url().$this->page_name."=".$i.">$i</a>" : $Nav .= "<span class=index_page>$i</span>";
				}
			}
			
			//下页,尾页
			if($this->index_page<$this->total_page)
			{
				$Nav .= "<A href=".$this->get_url().$this->page_name."=".($this->index_page+1).">".$this->next_page."</a>";
				$Nav .= "<A href=".$this->get_url().$this->page_name."=".$this->total_page.">".$this->last_page."</a>";
			}
			return $Nav;
		}
		
		//获得当前URL并对其参数进行重组
		function get_url()
		{
			
			//未指定URL则获取当前网址
			if(!isset($this->url))
			{
				$url = parse_url($_SERVER['REQUEST_URI']);
				$url = $url['path'];
			}else{
				$url = $this->url;
			}
			
			//循环当前的GET参数，并排除分页参数KEY
			foreach($_GET as $key => $value)
			{
				if($key!=$this->page_name)
				{
					$get .= $key."=".$value."&";
				}
			}
			
			//循环当前的POST参数
			foreach($_POST as $key => $value)
			{
				$get .= $key."=".$value."&";
			}
			
			//重组URL
			$url = $url."?".$get;
			return $url;
		}
		
		//错误处理
		function error($function,$errormsg)   
		{   
			die('Error in file <B>'.__FILE__.'</B> ,Function <B>'.$function.'()</B> :'.$errormsg);
		}   
	}
?>